//
//  UserAccount.swift
//  XNWeiBo_Swift
//
//  Created by xunan on 16/7/7.
//  Copyright © 2016年 xunan. All rights reserved.
//

import UIKit

// swift2.0要打印 需要CustomStringConvertible协议中的description 方法
class UserAccount: NSObject, NSCoding {
    var access_token: String?
    var expires_in: NSNumber? {
        didSet {
            expires_Date = NSDate(timeIntervalSinceNow: (expires_in?.doubleValue)!)
        }
    }
    var uid: String?

    
    var expires_Date : NSDate?
    
    var profile_image_url : NSString?
    
    var screen_name : String?
    
    var avatar_large : NSString?
    
    init(dict: [String:AnyObject])
    {
        super.init()
        setValuesForKeysWithDictionary(dict)
        
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        print(key)
    }
    
    override var description: String {
        // 定义属性数组
        let properties = ["access_token","expires_in","uid" ,"expires_Date" ,"screen_name" ,"avatar_large"];
        // 跟进属性转成字典
        let dict = self.dictionaryWithValuesForKeys(properties)
        // 字典转字符串
        return "\(dict)"
    }
    
    func loadUserInfo(finished: (account: UserAccount?, error:NSError?)->()) {
        
        assert(access_token != nil, "没有授权")

        
        let path = "2/users/show.json"
        let params = ["access_token": access_token!, "uid":uid!]
        NetworkTools.shareNetworkTools().GET(path, parameters: params, success: { (_, JSON) in
            
            if let dict = JSON as? [String : AnyObject] {
                self.screen_name = dict["screen_name"] as? String
                self.avatar_large = dict["avatar_large"] as? String
                
                finished(account: self, error: nil)
                return
            }
            
            finished(account: nil, error: nil)
            
            print(JSON)
            
            }) { (_, error) in
                print(error)
                finished(account: nil, error: error)
        }
    }
    
    /**
     返回是否登录过
     */
    class func userLogin() -> Bool {
        return UserAccount.loadAccount() != nil
    }
    
    static let filePath = "account.plist".cacheDir()
    /**
     保存
     */
    func saveAccount() {
        NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.filePath)
    }
    /**
     读取
     */
    // 静态的用户账号属性
    static var account: UserAccount?
    
    class func loadAccount() -> UserAccount? {
        
        if account != nil {
            return account
        }
        
        account = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as? UserAccount
        
        if account?.expires_Date?.compare(NSDate()) == NSComparisonResult.OrderedAscending  {
            return nil
        }
        
        return account
    }
    
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(expires_Date, forKey: "expires_Date")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")


    }
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeObjectForKey("expires_in") as? NSNumber
        uid = aDecoder.decodeObjectForKey("uid") as? String
        expires_Date = aDecoder.decodeObjectForKey("expires_Date") as? NSDate
        screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String

    }
}
